<?php
/*--------------------------------------------------------------------
 小微OA系统 - 让工作更轻松快乐

 Copyright (c) 2013 http://www.smeoa.com All rights reserved.

 Author:  jinzhu.yin<smeoa@qq.com>

 Support: https://git.oschina.net/smeoa/xiaowei
 --------------------------------------------------------------*/

// 后台用户模块
namespace Home\Controller;

class UserController extends HomeController {
	protected $config = array('app_type' => 'common','read'=>'select_dept','write'=>'password,reset_pwd,del_pwd');

	function _search_filter(&$map) {
		$keyword = I('keyword');
		if (!empty($keyword)) {
			$map['name|emp_no'] = array('like', "%" . $keyword . "%");
		}
	}

	public function index() {

        $list = M("Dept") -> where('is_del=0') -> order('sort asc') -> getField('id,name');
        $this -> assign('dept_list', $list);

        if (isset($_POST['eq_is_del'])) {
            $eq_is_del = $_POST['eq_is_del'];
        } else {
            $eq_is_del = "0";
        }
        $this -> assign('eq_is_del', $eq_is_del);

        $auth=$this->config['auth'];
        
        $this->assign('auth',$auth);
                
        $where_position['is_del']=array('eq',0);
        
        $map = $this -> _search();
        if($auth['admin']){
                        
        }elseif($auth['write']){                               
                $sub_dept = get_sub_dept();
                $map['dept_id'] = array('in', $sub_dept);
                $sub_position=get_sub_position(); 
                $where_position['id']=array('in',$sub_position);   
        }else{
            $this->error('没有权限');
        }
 
		$list = M("Position") -> where($where_position) -> order('sort asc') -> getField('id,name');
		$this -> assign('position_list', $list);
		
		
		if (method_exists($this, '_search_filter')) {
			$this -> _search_filter($map);
		}
		$map['is_del'] = array('eq', $eq_is_del);
 
		$model = M("User");

		if (!empty($model)) {
			$this -> _list($model, $map, "emp_no");
		}
		$this -> display();
	}

	public function add() {
        $auth=$this->config['auth'];                          
        $where_position['is_del']=array('eq',0);

        if($auth['admin']){
                        
        }elseif($auth['write']){                               
                $sub_dept = get_sub_dept();
                $map['dept_id'] = array('in', $sub_dept);
                $sub_position=get_sub_position(); 
                $where_position['id']=array('in',$sub_position);   
        }else{
            $this->error('没有权限');
        }

		$list =  M("Position") -> where($where_position) -> order('sort asc') -> getField('id,name');
		$this -> assign('position_list', $list);

		$model = M("Dept");
		$list = $model -> where('is_del=0') -> order('sort asc') -> getField('id,name');
		$this -> assign('dept_list', $list);

		$this -> display();
	}

	public function read($id) {
		$model = M('User');
		$field = 'id,emp_no,name,sex,birthday,dept_id,position_id,office_tel,mobile_tel,email,duty,is_del,pic';
		$vo = $model -> field($field) -> find($id);
		if (IS_AJAX) {
			if ($vo !== false) {// 读取成功
				$return['data'] = $vo;
				$return['status'] = 1;
				$return['info'] = "读取成功";
				$this -> ajaxReturn($return);
			} else {
				$return['status'] = 0;
				$return['info'] = "读取错误";
				$this -> ajaxReturn($return);
			}
		}
		$this -> assign('vo', $vo);
		$this -> display();
		return $vo;
	}

	// 检查帐号
	public function check_account() {
		if (!preg_match('/^[a-z]\w{4,}$/i', $_POST['emp_no'])) {
			$this -> error('用户名必须是字母，且5位以上！');
		}
		$User = M("User");
		// 检测用户名是否冲突
		$name = I('emp_no'); ;
		$result = $User -> getByAccount($name);
		if ($result) {
			$this -> error('该编码已经存在！');
		} else {
			$this -> assign('jumpUrl', get_return_url());
			$this -> success('该编码可以使用！');
		}
	}

	// 插入数据
	protected function _insert($name = "User") {
		// 创建数据对象
		$model = D("User");
		if (!$model -> create()) {
			$this -> error($model -> getError());
		} else {
			// 写入帐号数据
			$model -> letter = get_letter($model -> name);
			$model -> password = md5($model -> emp_no);
			$model -> dept_id = I('dept_id');
			$model -> openid = $model -> emp_no;
			$model -> westatus = 1;
			$emp_no = $model -> emp_no;
			$name = $model -> name;
			$mobile_tel = $model -> mobile_tel;

			if ($result = $model -> add()) {
				$data['id'] = $result;
				D("UserConfig") -> set_config($data);
				if (get_system_config('system_license')) {
					if (!empty($mobile_tel)) {
						//import("Weixin.ORG.Util.Weixin");
						//$weixin = new \Weixin();
						$mobile_tel = trim($mobile_tel, '+-');
						//$weixin -> add_user($emp_no, $name, $mobile_tel);
					}
				}
				$this -> assign('jumpUrl', get_return_url());
				$this -> success('用户添加成功！');
			} else {
				$this -> error('用户添加失败！');
			}
		}
	}

	protected function _update($name = "User") {
		$model = D($name);
		if (false === $model -> create()) {
			$this -> error($model -> getError());
		}
		$user_id = I('id');
		$model -> letter = get_letter($model -> name);        
		$emp_no = $model -> emp_no;
		$name = $model -> name;
		$mobile_tel = $model -> mobile_tel;
        $model -> openid = $model -> emp_no;
        $model -> westatus = 1;        
		$is_del = $model -> is_del;
		$list = $model -> save();
		if (false !== $list) {
			if (get_system_config('system_license')) {
                $mobile_tel = trim($mobile_tel, '+-');
				if (!empty($mobile_tel)) {
/* 					import("Weixin.ORG.Util.Weixin");
					$weixin = new \Weixin();				
					$weixin -> add_user($emp_no, $name, $mobile_tel);
					$weixin -> update_user($emp_no, $name, $mobile_tel, $is_del); */
				}
			}
			$this -> assign('jumpUrl', get_return_url());
			$this -> success('编辑成功!');
		} else {
			//错误提示
			$this -> error('编辑失败!');
		}
	}

	//重置密码
	public function reset_pwd() {
		$id = I('user_id');
		$password = md5(I('password'));
		if ('' == trim($password)) {
			$this -> error('密码不能为空!');
		}
		$where['id']=array('in',array_filter(explode(',', $id)));		
		$result = M('User')->where($where)->setField('password',$password);
		if ($result !== false) {
			if (C('LDAP_LOGIN')) {
				import("Home.ORG.Util.Ldap");
				$ldap_server = C('LDAP_SERVER');
				$ldap_port = C('LDAP_PORT');
				$ldap_user = C('LDAP_USER');
				$ldap_pwd = C('LDAP_PWD');
				$ldap_base_dn = C('LDAP_BASE_DN');

				$ldap = new \Ldap($ldap_server, $ldap_port, $ldap_user, $ldap_pwd, $ldap_base_dn);
				$emp_no = get_emp_no($id);

				$ldap -> reset_pwd($emp_no, $password);
				if (!$ldap -> status) {
					$this -> error($ldap -> info);
				}
			}
			$this -> assign('jumpUrl', get_return_url());
			$this -> success("密码修改成功");
		} else {
			$this -> error('重置密码失败！');
		}
	}

	function del_pwd() {
		$id = $_POST['user_id'];
		$User = M('User');
		$where['id'] = array('in', $id);
		$data['pay_pwd'] = '';
		$result = $User -> where($where) -> save($data);
		if (false !== $result) {
			$this -> assign('jumpUrl', get_return_url());
			$this -> success("密码清除成功");
		} else {
			$this -> error('清除密码失败！');
		}
	}

	public function password() {
		$this -> assign("id", I('id'));
		$this -> display();
	}

	function json() {
		header("Content-Type:text/html; charset=utf-8");
		$key = $_REQUEST['key'];

		$model = M("User");
		$where['name'] = array('like', "%" . $key . "%");
		$where['emp_no'] = array('like', "%" . $key . "%");
		$where['_logic'] = 'or';
		$map['_complex'] = $where;
		$list = $model -> where($map) -> field('id,name') -> select();
		exit(json_encode($list));
	}

	function del() {
		$id = I('user_id');
		$admin_user_list = C('ADMIN_USER_LIST');
 
		if (!empty($admin_user_list)) {
			$where['emp_no'] = array('not in', $admin_user_list);
		}
		$where['id'] = array('in', $id);

		$user_id = M("User") -> where($where) -> getField('id', TRUE);
		$emp_no = M("User") -> where($where) -> getField('emp_no', TRUE);

		if (get_system_config('system_license')) {
		/* 	import("Weixin.ORG.Util.Weixin");
			$weixin = new \Weixin();
			$restr = $weixin -> del_user($emp_no); */
		}
		if (C('LDAP_LOGIN')) {
			import("Home.ORG.Util.Ldap");
			$ldap_server = C('LDAP_SERVER');
			$ldap_port = C('LDAP_PORT');
			$ldap_user = C('LDAP_USER');
			$ldap_pwd = C('LDAP_PWD');
			$ldap_base_dn = C('LDAP_BASE_DN');

			$ldap = new \Ldap($ldap_server, $ldap_port, $ldap_user, $ldap_pwd, $ldap_base_dn);
			foreach ($emp_no as $val) {
				$ldap -> del_user($val);
			}
		}
		$this -> _destory($user_id);
	}

	public function import() {
		$opmode = I('opmode');
		if ($opmode == "import") {
			$import_user = array();
			$File = D('File');
			$file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
			$info = $File -> upload($_FILES, C('DOWNLOAD_UPLOAD'), C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$file_driver}_CONFIG"));
			if (!$info) {
				$this -> error('上传错误');
			} else {
				//取得成功上传的文件信息
				//$uploadList = $upload -> getUploadFileInfo();
				Vendor('Excel.PHPExcel');
				//导入thinkphp第三方类库

				$import_file = $info['uploadfile']["path"];
				$import_file = substr($import_file, 1);

				$objPHPExcel = \PHPExcel_IOFactory::load($import_file);

				$dept = M("Dept") -> getField('name,id');
				$position = M("Position") -> getField('name,id');
				$role = M("Role") -> getField('name,id');

				$sheetData = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);
				$model = D("User");
				for ($i = 2; $i <= count($sheetData); $i++) {
					$data = array();
					$data_user['emp_no'] = $sheetData[$i]["A"];
					$data_user['name'] = $sheetData[$i]["B"];

					$data_user['dept_id'] = $dept[$sheetData[$i]["C"]];
					$data_user['position_id'] = $position[$sheetData[$i]["D"]];

					$data_user['duty'] = $sheetData[$i]["J"];
					$data_user['office_tel'] = $sheetData[$i]["F"];
					$data_user['mobile_tel'] = $sheetData[$i]["G"];
					$data_user['sex'] = $sheetData[$i]["H"];
					$data_user['birthday'] = $sheetData[$i]["I"];
					$data_user['openid'] = $sheetData[$i]["A"];
					$data_user['westatus'] = 1;
					$data_user['password'] = md5($sheetData[$i]["A"]);

					if (empty($data_user['emp_no'])) {
						$error[$i] = $sheetData[$i];
						$error[$i]['desc'] = '员工编号不能为空';
						continue;
					}
					if (empty($data_user['name'])) {
						$error[$i] = $sheetData[$i];
						$error[$i]['desc'] = '姓名不能为空';
						continue;
					}
					if (empty($data_user['dept_id'])) {
						$error[$i] = $sheetData[$i];
						$error[$i]['desc'] = '部门不能为空';
						continue;
					}
					if (empty($data_user['dept_id'])) {
						$error[$i] = $sheetData[$i];
						$error[$i]['desc'] = '部门不能为空';
						continue;
					}

					if (empty($data_user['position_id'])) {
						$error[$i] = $sheetData[$i];
						$error[$i]['desc'] = '职位不能为空';
						continue;
					}

					$where_check['emp_no'] = array('eq', $sheetData[$i]["A"]);
					$check_count = D('User') -> where($where_check) -> count();

					if (!empty($check_count)) {
						$error[$i] = $sheetData[$i];
						$error[$i]['desc'] = '用户已存在';
						continue;
					}

					$user_id = M("User") -> add($data_user);
					$import_user[] = $sheetData[$i]["A"];

					$role_list = array_filter(explode(',', $sheetData[$i]["E"]));
					$data_role = array();

					foreach ($role_list as $key => $val) {
						$data_role[] = $role[$val];
					}
					$this -> add_role($user_id, $data_role);
				}
				if (!empty($import_user)) {
				//	$this -> _weixin_sync($import_user);
					$this -> _sync_to_ldap($import_user);
				}

				$this -> assign('jumpUrl', get_return_url());
				if (empty($error)) {
					$this -> success('导入成功！');
					die ;
				} {
					$this -> assign('error', $error);
					$this -> display('error');
					die ;
				}
			}
		} else {
			$this -> display();
		}
	}

    function ad_sync() {
        
        $ldap_host = C("LDAP_SERVER");
        $ldap_port = C("LDAP_PORT");
        $ldap_user = C("LDAP_USER"); 
        $ldap_pwd = C("LDAP_PWD"); 
        $ldap_base_dn=C('LDAP_BASE_DN');
        $ldap_map=C('LDAP_MAP');
        $is_ad=C('IS_AD');
        
        $ldap_conn = ldap_connect($ldap_host, $ldap_port) //建立与 LDAP 服务器的连接
        or die("Can't connect to LDAP server");
        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION,3);
 
        $r=ldap_bind($ldap_conn, $ldap_user, $ldap_pwd) or die(ldap_error($ldap_conn));//与服务器绑定
        $base_dn = $ldap_base_dn;//定义要进行查询的目录主键

        $filter_val=C("LDAP_FILTER");
 
        $base_dn=$ldap_base_dn;
            
        $result= ldap_search($ldap_conn, $base_dn,$filter_val,$attr);//执行查询
        $entry= ldap_get_entries($ldap_conn,$result);//获得查询结果
 
        $dept_list=M("Dept")->getField("name,id");
        $position_list=M("Position")->getField("name,id");
        
        foreach($entry as $item){
            if(is_array($item)){
                $where['emp_no']=array('eq',$item[$ldap_map['emp_no']][0]);
                $user=M('User')->where($where)->select();  
               
                if (empty($user)) {
                    
                    $data['emp_no']=$item[$ldap_map['emp_no']][0];
                    $data['name']=$item[$ldap_map['name']][0];
                    $data['letter']=get_letter($item[$ldap_map['name']][0]);
                    $data['email']=$item[$ldap_map['name']][0];
                    
                    if(!empty($ldap_map['dept_name'])){
                        $data['dept_id']=$dept_list[$item[$ldap_map['dept_name']][0]];    
                    }
                    if(!empty($ldap_map['position_name'])){
                        $data['position_id']=$position_list[$item[$ldap_map['position_name']][0]];
                    }
                    
                    if($is_ad){
                        $is_del=$item['useraccountcontrol'][0];                         
                        if(fmod($is_del,8)==2){
                            $data['is_del']=1;
                        }else{
                            $data['is_del']=0;
                        }
                    }

                    $rs=M("User")->add($data);      
                    $new_count++;   
                    $new_data[]=$data;
                }
            }
        }
        $this->assign("new_count",$new_count);
        $this->assign("new_data",$new_data);

        $this -> display();
    }

	private function _weixin_sync($user_list) {
		if (get_system_config('system_license')) {
			import("Weixin.ORG.Util.Weixin");
			$weixin = new \Weixin($agent_id);

			$where['emp_no'] = array('in', $user_list);
			$where['is_del'] = array('eq', 0);
			$user_list = M("User") -> where(array('is_del' => 0)) -> getField('emp_no,name,mobile_tel');

			$error_code_desc = C('WEIXIN_ERROR_CODE');

			foreach ($user_list as $key => $val) {
				$emp_no = $val['emp_no'];
				$name = $val['name'];
				$mobile_tel = trim($val['mobile_tel'], '+-');
				$error_code =          json_decode($weixin -> add_user($emp_no, $name, $mobile_tel)) -> errcode;

				$list[$key]['error_code'] = $error_code;
				$list[$key]['desc'] = $error_code_desc[$error_code];
				$list[$key]['emp_no'] = $key;
			}
			$this -> assign('weixin_list', $list);
		}
	}

	private function _sync_to_ldap($user_list) {
		if (C('LDAP_LOGIN')) {
			import("Home.ORG.Util.Ldap");
			$ldap_server = C('LDAP_SERVER');
			$ldap_port = C('LDAP_PORT');
			$ldap_user = C('LDAP_USER');
			$ldap_pwd = C('LDAP_PWD');
			$ldap_base_dn = C('LDAP_BASE_DN');
			$ldap = new \Ldap($ldap_server, $ldap_port, $ldap_user, $ldap_pwd, $ldap_base_dn);
			$list = $ldap -> sync_to_ldap($user_list);

			$this -> assign('ldap_list', $list);
		}
	}

	function add_role($user_id, $role_list) {
		$data['user_id'] = $user_id;

		foreach ($role_list as $role_id) {
			$data['role_id'] = $role_id;
			M('RoleUser') -> add($data);
		}
	}

    function select_dept(){
        $auth=$this->config['auth'];        
        $node = M("Dept");
        $menu = array();
        $where['is_del']=array('eq',0);
        if($auth['admin']){
            $root=0;
        }elseif($auth['write']){
            $sub_dept=get_sub_dept();            
            $where['id']=array('in',$sub_dept);
            $root=get_dept_id();
            $this->assign('write',true);
        }else{
            $this->error('没有权限');
        }
        
        $menu = $node -> where($where) -> field('id,pid,name') -> order('sort asc') -> select();        
        $tree = list_to_tree($menu,$root);
        $this -> assign('menu', popup_tree_menu($tree));
        
        $pid = array();
        $this -> assign('pid', $pid);
        $this -> display();
    }
}
?>